//
//  PVDDetailModel.swift
//  ezyform
//
//  Created by MoennigQ on 16/5/18.
//  Copyright © 2018 Client.Solution Pty Ltd. All rights reserved.
//

import UIKit
import HandyJSON
class PVDDetailModel: HandyJSON {
    var pvd_id : Int64?
    var id: String {
        return String(pvd_id ?? 0)
    }
    var gst: Bool?
    var gwt_id: String?
    //job status: 0 is scheduled; 1: installing; 2 installed; 3 unqulified
    var job_status: String?
    //retailer company name
    var company: String?
    var company_electrical_contractor_license_number: String?
    var company_electrical_contractor_Name: String?
    var company_electrical_contractor_phone_number: String?
    //SPV
    var company_spv_check: Bool = false //retailer设置的是否开启SPV的值
    var installation_position_deviation: Double? //系统设置的panel number的安装位置和最初位置偏移的最大距离，单位是米
    var spv_check: Bool? //当前Job是否开启SPV
    var spv_installed: Bool? //当前Job 的Panel Number是否安装完成，验证通过
    var der_register: Bool = false//true: checklist中最后一条或finish job成功后的弹出框显示der register；false表示不显示
    //
    var arrived_at: String?
    var arrived_location: String?
    var finished_at: String?
    var finished_location: String?
    var installer_job_site_instruction: String?
    var pick_up_required: Bool = false
    var pick_up_reference: String = ""
    var delivery_address: DeliveryAddressModel?
    //owner address
    var owner_address: InstallationDetailOwnerAddress?
    
    //real install address
    var install_address: InstallationDetailInstallAddress?
    
    //solar system detail
    var system_detail: InstallationDetailSystemDetail?
    
    //checklist
    var pvd_checklists: [PVDChecklistModel] = [PVDChecklistModel]() {
        didSet {
            //0.先缓存，在一个增加
            var cacheChecklist = pvd_checklists
            pvd_checklists.removeAll()
            //1.*************Pre-Installation selfie
            if let findIndex = cacheChecklist.firstIndex(where: { checkModel in checkModel.id ==  ChecklistFixedId.preInstall.rawValue
            }){
                let checkModel = cacheChecklist[findIndex]
                checkModel.section = 1
                pvd_checklists.append(checkModel)//
                cacheChecklist.remove(at: findIndex)//删除
            }
            //2.*************扫描Panel Number和Inverter Number的
            let scanChecklist = PVDChecklistModel()
            scanChecklist.type = ChecklistType.Scan.rawValue
            scanChecklist.title = ""
            scanChecklist.section = 2
            pvd_checklists.append(scanChecklist)
            //3.*************Mid-Installation selfie
            if let findIndex = cacheChecklist.firstIndex(where: { checkModel in checkModel.id ==  ChecklistFixedId.midInstall.rawValue
            }){
                let checkModel = cacheChecklist[findIndex]
                checkModel.section = 3
                pvd_checklists.append(checkModel)//
                cacheChecklist.remove(at: findIndex)//删除
            }
            //4.*************checklist
            // 暂存endOfInstallationChecklist
            var endOfInstallationChecklist: PVDChecklistModel!
            if let findIndex = cacheChecklist.firstIndex(where: { checkModel in checkModel.id ==  ChecklistFixedId.testAndCommission.rawValue
            }){
                endOfInstallationChecklist = cacheChecklist[findIndex]
                cacheChecklist.remove(at: findIndex)//删除
            }
            // 暂存certificateOfElectricalSafety
            var cesChecklist: PVDChecklistModel!
            if let findIndex = cacheChecklist.firstIndex(where: { checkModel in checkModel.id ==  ChecklistFixedId.certificateOfElectricalSafety.rawValue
            }){
                cesChecklist = cacheChecklist[findIndex]
                cacheChecklist.remove(at: findIndex)//删除
            }
            //将cacheChecklist剩下的都加载Checklist这一组的最后边
            for checkModel in cacheChecklist{
                checkModel.section = 4
                pvd_checklists.append(checkModel)
            }
            //  der register加在Checklist最后
            if self.der_register {//如果开启der register，加入到最好一行行
                let derChecklist = PVDChecklistModel()
                derChecklist.title = "DER Register"
                derChecklist.is_required = "false"
                derChecklist.type = ChecklistType.DerRegister.rawValue
                derChecklist.section = 4
                pvd_checklists.append(derChecklist)
            }
            //5.*************End of installation
            if let _ = endOfInstallationChecklist{
                endOfInstallationChecklist.section = 5
                pvd_checklists.append(endOfInstallationChecklist)
            }
            //6.*************CERTIFICATES
            //Panel Installed步骤
            if let data = self.spv_check ,data {//如果开启SPV，将Panel Installed加入到第一行
                let spvChecklist = PVDChecklistModel()
                spvChecklist.is_required = "true"
                spvChecklist.title = ""
                spvChecklist.type = ChecklistType.PanelInstalled.rawValue
                spvChecklist.section =  6
                pvd_checklists.append(spvChecklist)
            }
            //End of installation
            if let _ = cesChecklist{
                cesChecklist.section = 6
                pvd_checklists.append(cesChecklist)
            }
            InstallationDetailVCHelper.shared().getLocalCheckList(self)
        }
    }
    //local checklist data
    var localChecklists: [PVDChecklistModel] = [PVDChecklistModel]()
    
    //***********New serial numbers in child table
    var pvd_serial_numbers: [PanelNumberImageDBModel] = [PanelNumberImageDBModel]()
    //for split serial numbers to child table
    var localPVDSerialNumbers = [PanelNumberImageDBModel]()
    //*****modifed or deleted panelnumbers from server
    var localModifiedSerialNumbers = [PanelNumberImageDBModel]()
    var localDeletedSerialNumbers = [PanelNumberImageDBModel]()
    
    //***********New serial numbers in child table
    var pvd_inverter_serial_numbers: [PanelNumberImageDBModel] = [PanelNumberImageDBModel]()
    //for split inverter numbers to child table
    var localPVDInverterNumbers = [PanelNumberImageDBModel]()
    //*****modifed or deleted panelnumbers from server
    var localModifiedInverterNumbers = [PanelNumberImageDBModel]()
    var localDeletedInverterNumbers = [PanelNumberImageDBModel]()
    //************
    
    //owner,designer,installer signature
    var signatures: InstallationDetailSignatures?
    
    //local siginatures
    var localSignatures: PVDSignaturesLocalModel = PVDSignaturesLocalModel()
    
    //local signatures info (signed time, witness's print name)
    var localSignaturesInfo = NSMutableDictionary()

    //check if signatures is modified
    var signaturesModifyFlag: Bool = false
    
    //check if panel numbers is modified
    var panelNumbersModifyFlag: Bool = false
    //check if inverter numbers is modified
    var inverterNumbersModifyFlag: Bool = false
    //only check if checklist is modidfied
    var checkListModifyFlag: Bool = false
    //only check if installation address and date of completion
    var detailModifyFlag: Bool = false
    
    var stc_document : InstallationAttachmentModel?
    var coc_document : InstallationAttachmentModel?
    var invoice_document : InstallationAttachmentModel?
    var other_document: [InstallationAttachmentModel]?
    //have multiple attachments,use new parameter
    var stc_documents : [InstallationAttachmentModel]?
    var coc_documents : [InstallationAttachmentModel]?
//    var invoice_documents : [InstallationAttachmentModel]?//不让installer看到这些敏感信息，3.6.0版本去掉
    var notice_of_completion_documents: [InstallationAttachmentModel]?
    //当前用户是否是Installer，true表示是可以有所有操作权限，false表示否，即当前用户是designer只能前自己的签名
    var isInstallerFlag: Bool {
        if let _ = signatures {//signatures不为空
            if let installerAccreditation = signatures?.installer_accredited_number, let currentAccreditation = APPConfig.loginInfo.accreditedNumber,installerAccreditation != "" &&  currentAccreditation != "" {//installer,designer和当前登录用户的accreditation number都不会null且都不会空字符串
                //如果当前登录用户的accreditation和installer的是一致的就是installer
                if currentAccreditation == installerAccreditation{
                    return true
                }
            }
        }
        return false
    }
    //当前用户是否是designer，true表示是
    var isDesignerFlag: Bool {
        if let _ = signatures {//signatures不为空
            if let designerAccreditation = signatures?.designer_accredited_number, let currentAccreditation = APPConfig.loginInfo.accreditedNumber, designerAccreditation != "" && currentAccreditation != "" {//installer,designer和当前登录用户的accreditation number都不会null且都不会空字符串
                //如果当前登录用户的accreditation和installer，designer的都不一致，就表示当前用户没有任何操作权限
                if currentAccreditation == designerAccreditation{
                    return true
                }
            }
        }
        return false
    }
    
    //电工表的链接路径，为null 或 '' 就不显示checklist中的，有路径的时候就显示
    var electrical_template: String?
    //true表示当前company是Aus Solar Co，在Owner签名时需要多前连个满意度form
    var is_aus_solar_co: Bool?
    //Owner签字时选择的
    var physicallyAttended: String?
    //finish Job成功后是否弹出APP评分的标识,不为空就弹出App comment，空值不弹出
    var installer_rating_id: Int?//
    //true表示使用老的owner协议，否则使用新的owner协议
    var is_aho: Bool?
    // is_new_stc_form 为 true ,表示使用新的协议，aho的协议版本传3，其他协议版本传4
    var is_new_stc_form: Bool?
    var agent_id: Int?
    // is_osw_agent 为 true ,表示agent是OSW，false表示agent是非OSW，用于区分owner的mandatory_declaration
    var is_osw_agent: Bool {
        if agent_id == 1 || agent_id == 2 {
            return true
        }
        return false
    }
    var agent_name: String?
    var re_sign_statement_message: String?//如果不为空就是需要重新签名，需要提示
    //Installer,Designer是否同一个人且可以合并签名
    var isInstallerAndDesigner: Bool {
        if let flag = self.is_new_stc_form, flag {//首先必须是新协议
            if let installerAccNumber = signatures?.installer_accredited_number, let designerAccNumber = signatures?.designer_accredited_number, let designerAccType = signatures?.designer_accreditation_type, installerAccNumber == designerAccNumber && designerAccType.lowercased().contains("design"){//accredited_number相同，且designer有design资质
                return true
            }
        }
        return false
    }
    //当前登录角色是Designer，是否能签名
    var canDesignerSignFlag: Bool {
        let jobStatus = self.job_status ?? ""
        if jobStatus != "0" &&  jobStatus != "2" && self.isDesignerFlag{//jobstatus不是scheduled,不是installed，而且当前用户是installater才能编辑pvd detail 信息
            return true
        }
        return false
    }
    //用于判断是否可以编辑Owner info, inverter ,battery,  installation type, grid connected
    var canEditPVDDetailFlag: Bool {
        let jobStatus = self.job_status ?? ""
        if jobStatus != "0" &&  jobStatus != "2" && self.isInstallerFlag{//jobstatus不是scheduled,不是installed，而且当前用户是installater才能编辑pvd detail 信息
            return true
        }
        return false
    }
    //用于判断是否可以编辑panel info
    var canEditPanelInfoFlag: Bool {
        let jobStatus = self.job_status ?? ""
        let spvCheckFlag = self.spv_check ?? false
        let spvInstalled = self.spv_installed ?? false
        if spvCheckFlag && spvInstalled {//panel installed之后不能编辑panel info
            return false
        }else if jobStatus != "0" &&  jobStatus != "2" && self.isInstallerFlag{//jobstatus不是scheduled,不是installed，而且当前用户是installater才能编辑panel info信
            return true
        }
        return false
    }
    var agreenments:PVDDetailAgreenmentsModel?
    required init(){}
    
    func copyAllValuesOfModel(_ newModel: PVDDetailModel){
        self.pvd_id = newModel.pvd_id
        self.gwt_id = newModel.gwt_id
        self.job_status = newModel.job_status
        self.company = newModel.company
        self.agent_name = newModel.agent_name
        self.company_electrical_contractor_license_number = newModel.company_electrical_contractor_license_number
        self.company_electrical_contractor_Name = newModel.company_electrical_contractor_Name
        self.company_electrical_contractor_phone_number = newModel.company_electrical_contractor_phone_number
        self.company_spv_check = newModel.company_spv_check
        self.installation_position_deviation = newModel.installation_position_deviation
        self.spv_check = newModel.spv_check
        self.spv_installed = newModel.spv_installed
        self.der_register = newModel.der_register
        self.arrived_at = newModel.arrived_at
        self.arrived_location = newModel.arrived_location
        self.finished_at = newModel.finished_at
        self.finished_location = newModel.finished_location
        self.owner_address = newModel.owner_address
        self.install_address = newModel.install_address
        self.system_detail = newModel.system_detail
        self.pvd_checklists = newModel.pvd_checklists
        self.localChecklists = newModel.localChecklists
        self.pvd_serial_numbers = newModel.pvd_serial_numbers
        self.localPVDSerialNumbers = newModel.localPVDSerialNumbers
        self.localModifiedSerialNumbers = newModel.localModifiedSerialNumbers
        self.localDeletedSerialNumbers = newModel.localDeletedSerialNumbers
        self.pvd_inverter_serial_numbers = newModel.pvd_inverter_serial_numbers
        self.localPVDInverterNumbers = newModel.localPVDInverterNumbers
        self.localModifiedInverterNumbers = newModel.localModifiedInverterNumbers
        self.localDeletedInverterNumbers = newModel.localDeletedInverterNumbers
        self.signatures = newModel.signatures
        self.localSignatures = newModel.localSignatures
        self.localSignaturesInfo = newModel.localSignaturesInfo
        self.signaturesModifyFlag = newModel.signaturesModifyFlag
        self.inverterNumbersModifyFlag = newModel.inverterNumbersModifyFlag
        self.checkListModifyFlag = newModel.checkListModifyFlag
        self.detailModifyFlag = newModel.detailModifyFlag
        self.stc_document = newModel.stc_document
        self.coc_document = newModel.coc_document
        self.invoice_document = newModel.invoice_document
        self.other_document = newModel.other_document
        self.stc_documents = newModel.stc_documents
        self.coc_documents = newModel.coc_documents
        self.notice_of_completion_documents = newModel.notice_of_completion_documents
        self.electrical_template = newModel.electrical_template
        self.is_aus_solar_co = newModel.is_aus_solar_co
        self.physicallyAttended = newModel.physicallyAttended
        self.installer_rating_id = newModel.installer_rating_id
        self.is_aho = newModel.is_aho
        self.is_new_stc_form = newModel.is_new_stc_form
        self.agent_id = newModel.agent_id
        self.re_sign_statement_message = newModel.re_sign_statement_message
        self.gst = newModel.gst
        self.agreenments = newModel.agreenments
        self.installer_job_site_instruction = newModel.installer_job_site_instruction
        self.pick_up_required = newModel.pick_up_required
        self.pick_up_reference = newModel.pick_up_reference
        self.delivery_address = newModel.delivery_address
        //获取本地数据
        InstallationDetailVCHelper.shared().getAllLocalData(self)
    }
}

class PVDDetailAgreenmentsModel: HandyJSON {
    var designer: String?
    var installer: String?
    var owner: String?
    //需要翻墙，因为H5中有s3上的脚本
    //1.installer开头的协议，installer_index.html
    var installerStatementUrlStr: String {
        var urlStr: String = ""//本地测试的链接，发布时要删除installer_index.html
        if APPConfig.OnlineStatementFlag {//Online
            if let data = installer {
                urlStr = APPConfig.serverAddress + data
            }
        }else {//local,主要用于本地测试
            urlStr = "agreement/installer/installer_index"
        }
        return urlStr
    }
    //2.installer开头的协议，designer_index.html
    var designerStatementUrlStr: String {
        var urlStr: String = ""//本地测试的链接，发布时要删除designer_index.html
        if APPConfig.OnlineStatementFlag {//Online
            if let data = designer {
                urlStr = APPConfig.serverAddress + data
            }
        }else {//local,主要用于本地测试
            urlStr = "agreement/designer/designer_index"
        }
        return urlStr
    }
    //3.owner开头的协议，owner_index.html
    var ownerStatementUrlStr: String {
        var urlStr: String = ""//本地测试的链接，发布时要删除owner_index.html
        if APPConfig.OnlineStatementFlag {//Online
            if let data = owner {
                urlStr = APPConfig.serverAddress + data
            }
        }else {//local,主要用于本地测试
            urlStr = "agreement/owner/owner_index"
        }
        return urlStr
    }
    required init(){}
}
